package ncut.shumei.service.impl;

import ncut.shumei.dao.UserDao;
import ncut.shumei.dto.UserCreateRequest;
import ncut.shumei.dto.UserDTO;
import ncut.shumei.dto.UserUpdateRequest;
import ncut.shumei.entity.User;
import ncut.shumei.exception.BusinessException;
import ncut.shumei.exception.ResourceNotFoundException;
import ncut.shumei.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserDao userDao;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User register(UserCreateRequest request) {
        try {
            // 检查用户名是否已存在
            if (userDao.findByUsername(request.getUsername()) != null) {
                throw new BusinessException("Username already exists");
            }

            // 创建新用户
            User user = new User();
            user.setUsername(request.getUsername());
            user.setPassword(passwordEncoder.encode(request.getPassword()));
            user.setPhone(request.getPhone());
            user.setEmail(request.getEmail());
            user.setRole("USER");
            user.setStatus(1);

            // 保存用户
            userDao.insert(user);
            
            // 清除密码后返回
            user.setPassword(null);
            return user;
        } catch (Exception e) {
            log.error("Registration failed", e);
            throw new BusinessException("Registration failed: " + e.getMessage());
        }
    }

    @Override
    public List<UserDTO> getUsers(String role, Integer status) {
        List<User> users = userDao.findAll(role, status);
        return users.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public UserDTO getUser(Integer id) {
        User user = userDao.findById(id);
        if (user == null) {
            throw new ResourceNotFoundException("User not found with id: " + id);
        }
        return convertToDTO(user);
    }

    @Override
    public UserDTO createUser(UserCreateRequest request) {
        if (userDao.findByUsername(request.getUsername()) != null) {
            throw new BusinessException("Username already exists");
        }

        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        user.setRole("USER");
        user.setStatus(1);

        userDao.insert(user);
        return convertToDTO(user);
    }

    @Override
    public UserDTO updateUser(Integer id, UserUpdateRequest request) {
        User user = userDao.findById(id);
        if (user == null) {
            throw new ResourceNotFoundException("User not found with id: " + id);
        }

        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        if (request.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(request.getPassword()));
        }

        userDao.update(user);
        return convertToDTO(user);
    }

    @Override
    public void deleteUser(Integer id) {
        User user = userDao.findById(id);
        if (user == null) {
            throw new ResourceNotFoundException("User not found with id: " + id);
        }
        if ("ADMIN".equals(user.getRole())) {
            throw new BusinessException("Cannot delete admin user");
        }
        userDao.delete(id);
    }

    @Override
    public void updateUserStatus(Integer id, Integer status) {
        User user = userDao.findById(id);
        if (user == null) {
            throw new ResourceNotFoundException("User not found with id: " + id);
        }
        if ("ADMIN".equals(user.getRole())) {
            throw new BusinessException("Cannot update admin user status");
        }
        userDao.updateStatus(id, status);
    }

    @Override
    public void updateLoginTime(Integer id) {
        userDao.updateLoginTime(id);
    }

    private UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setPhone(user.getPhone());
        dto.setEmail(user.getEmail());
        dto.setRole(user.getRole());
        dto.setStatus(user.getStatus());
        dto.setCreatedAt(user.getCreatedAt());
        dto.setUpdatedAt(user.getUpdatedAt());
        return dto;
    }
} 